<template>
  <el-dialog :visible.sync="visible" v-if="visible" :title="title">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" :disabled="formData.id?true:false" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入昵称"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="角色" prop="roleId" v-if="!info">
        <el-select style="width: 100%" v-model="formData.roleId" clearable filterable placeholder="选择角色" @change="roleChange">
          <el-option v-for="role in roleList" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" v-if="(formData.roleId === 2 || formData.roleId === 3) && !info">
        <el-select style="width: 100%" v-model="formData.departmentId" clearable filterable placeholder="选择部门">
          <el-option v-for="department in departmentList" :key="department.id" :label="department.departmentName" :disabled="department.status === 2" :value="department.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="驾照" v-if="formData.roleId !== 4">
        <el-radio-group v-model="formData.isDriver">
          <el-radio :label="2">无驾照</el-radio>
          <el-radio :label="1">有驾照</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="formData.isDriver === 1">
        <el-form-item label="驾照正面">
          <el-upload :action="uploadUrl" :headers="uploadHeader" :limit="1" :file-list="photo1FileList" list-type="picture-card" ref="driverPhoto1" :on-success="photo1Success" :before-upload="beforeUpload" :on-exceed="onExceed">
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}" style="height: 100%;width: 100%">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <div class="el-upload-list__item-actions">
                <span @click="showImage(file)"><i class="el-icon-zoom-in"></i></span>
                <span @click="removeImage(file,'driverPhoto1')"><i class="el-icon-delete"></i></span>
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="驾照反面">
          <el-upload :action="uploadUrl" :headers="uploadHeader" :limit="1" :file-list="photo2FileList" list-type="picture-card" ref="driverPhoto2" :on-success="photo2Success" :before-upload="beforeUpload" :on-exceed="onExceed">
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}" style="height: 100%;width: 100%">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <div class="el-upload-list__item-actions">
                <span @click="showImage(file)"><i class="el-icon-zoom-in"></i></span>
                <span @click="removeImage(file,'driverPhoto2')"><i class="el-icon-delete"></i></span>
              </div>
            </div>
          </el-upload>
        </el-form-item>
      </template>
      <el-form-item label="头像">
        <el-upload :action="uploadUrl" :headers="uploadHeader" :limit="1" :file-list="avatarFileList" list-type="picture-card" ref="avatar" :on-success="avatarSuccess" :before-upload="beforeUpload" :on-exceed="onExceed">
          <i class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}" style="height: 100%;width: 100%">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <div class="el-upload-list__item-actions">
              <span @click="showImage(file)"><i class="el-icon-zoom-in"></i></span>
              <span @click="removeImage(file,'avatar')"><i class="el-icon-delete"></i></span>
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="状态" v-if="!info">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">可用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="imageDialog" title="查看图片" v-if="imageDialog" append-to-body>
      <a :href="imageSrc" target="_blank" title="点击查看原图" style="display: block;height: 100%;width: 100%">
        <img :src="imageSrc" alt="" style="display: block;height: 100%;width: 100%">
      </a>
    </el-dialog>
  </el-dialog>
</template>

<script>
const formData = {
  id: '',
  username: '',
  nickname: '',
  phone: '',
  status: 1,
  roleId: '',
  departmentId: '',
  avatar: 'avatar.png',
  isDriver: 2,
  driverPhoto1: '',
  driverPhoto2: ''
}
export default {
  name: 'UserinfoUpdate',
  data () {
    return {
      visible: false,
      title: '添加数据',
      formData,
      rules: {
        username: [{
          required: true,
          message: '用户名不能为空'
        }],
        nickname: [{
          required: true,
          message: '昵称不能为空'
        }],
        phone: [{
          required: true,
          message: '手机号不能为空'
        }, {
          pattern: /^1[0-9]{10}$/,
          message: '手机号码格式错误'
        }],
        roleId: [{
          required: true,
          message: '请选择角色'
        }]
      },
      roleList: [],
      departmentList: [],
      baseImage: process.env.VUE_APP_IMAGE_URL,
      uploadUrl: process.env.VUE_APP_URL + 'upload',
      uploadHeader: {
        token: this.$cookies.get('token')
      },
      avatarFileList: [],
      photo1FileList: [],
      photo2FileList: [],
      imageDialog: false,
      imageSrc: '',
      info: false
    }
  },
  methods: {
    init (id, info = false) {
      this.info = info
      this.visible = true
      this.title = id ? '修改数据' : '添加数据'
      this.formData = { ...formData }
      this.getDepartmentList()
      this.getRoleList()
      this.avatarFileList.length = 0
      this.photo1FileList.length = 0
      this.photo2FileList.length = 0
      if (id) {
        this.$http.get(`userinfo/info/${id}`).then(data => {
          if (data) {
            this.formData = { ...data }
            this.avatarFileList.push({ url: this.baseImage + data.avatar })
            if (data.isDriver === 1) {
              this.photo1FileList.push({ url: this.baseImage + data.driverPhoto1 })
              this.photo2FileList.push({ url: this.baseImage + data.driverPhoto2 })
            }
          }
        })
      }
    },
    getRoleList () {
      this.$http.get('role/select').then(data => {
        this.roleList = [...data]
      })
    },
    getDepartmentList () {
      this.$http.get('department/select').then(data => {
        this.departmentList = [...data]
      })
    },
    onExceed () {
      this.$message.error('超出个数限制！')
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isImage) {
        this.$message.error('请上传图片，格式支持：jpg,jpeg,png,gif')
      }
      const isLt20M = (file.size / 1024 / 1024) < 20
      if (!isLt20M) {
        this.$message.error('图片大小不能超过20MB')
      }
      return isImage && isLt20M
    },
    avatarSuccess (res) {
      if (res.code === 200) {
        this.formData.avatar = res.data
      } else {
        this.$message.error(`上传异常:{${res.msg}}`)
      }
    },
    photo1Success (res) {
      if (res.code === 200) {
        this.formData.driverPhoto1 = res.data
      } else {
        this.$message.error(`上传异常:{${res.msg}}`)
      }
    },
    photo2Success (res) {
      if (res.code === 200) {
        this.formData.driverPhoto2 = res.data
      } else {
        this.$message.error(`上传异常:{${res.msg}}`)
      }
    },
    removeImage (file, ref) {
      this.$confirm('确定删除该图片吗?', '询问', { type: 'info' }).then(() => {
        this.formData[ref] = ''
        this.$refs[ref].handleRemove(file)
      }).catch(() => {})
    },
    showImage (file) {
      this.imageDialog = true
      this.imageSrc = file.url
    },
    submit () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.formData.isDriver === 1) {
            if (!(this.formData.driverPhoto1 && this.formData.driverPhoto2)) {
              this.$message.error('请上传驾照！')
              return
            }
          } else {
            this.formData.driverPhoto1 = ''
            this.formData.driverPhoto2 = ''
          }
          this.$http.post('userinfo/update', this.formData).then(() => {
            this.$message.success('操作成功')
            this.visible = false
            this.$emit('closeDialog')
          }).catch(() => {})
        }
      })
    },
    roleChange (val) {
      if (val === 4) {
        this.formData.isDriver = 1
      }
    }
  }
}
</script>

<style scoped>

</style>
